$(function () {

    //失去焦点
    blurAllInput();
    //获取焦点
    focusAllInput();
});

//获取焦点
function focusAllInput(){
    $("#userName").focus(function () {
        $("#userName").attr("placeholder", "");
        $("#userName").removeClass("is-invalid is-valid");
    });
    $("#userEmail").focus(function () {    //当输入框获得焦点时
        $("#userEmail").attr("placeholder", "");
        $("#userEmail").removeClass("is-invalid is-valid");
    });
    $("#pwd").focus(function () {
        $("#pwd").attr("placeholder", "");
        $("#pwd").removeClass("is-invalid is-valid");
    });
    $("#reloadPwd").focus(function () {
        $("#reloadPwd").attr("placeholder", "");
        $("#reloadPwd").removeClass("is-invalid is-valid");
    });
    $("#emailCode").focus(function () {
        $("#emailCode").attr("placeholder", "");
        $("#emailCode").removeClass("is-invalid is-valid");
    });
    $("#email-user").focus(function () {
        $("#email-user").attr("placeholder", "");
        $("#email-user").removeClass("is-invalid is-valid");
    });

}

//失去焦点
function blurAllInput(){
    $("#userName").blur(function () {    //当输入框失焦时触发
        initUserName();
    });
    //邮箱
    $("#userEmail").blur(function () {
        initEmail();
    });
    $("#pwd").blur(function () {
        initPwd();
    });
    $("#reloadPwd").blur(function () {
        initReloadPwd();
    });
    $("#emailCode").blur(function () {
        initEmailCode();
    });
    $("#email-user").blur(function () {
        initEmailUser();
    });
}

function initUserName(){
    $("#userName").attr("placeholder", "用户名");
    var userName = $("#userName").val();
    let containSpecial = RegExp(/[(\ )(\~)(\~)(\!)(\！)(\@)(\#)(\$)(\￥)(\%)(\^)(\……)(\&)(\*)(\()(\（)(\))(\）)(\-)(\_))(\——)(\+)(\=)(\[)(\【)(\])(\】)(\{)(\})(\|))(\、))(\)(\\)(\;)(\；)(\:)(\：)(\')(\‘)(\’)(\")(\“)(\”)(\,)(\，)(\.)(\。)(\/)(\《)(\<)(\>)(\》)(\?)(\？)(\)]+/);
    //判断邮箱是否为空
    if(userName === "" || userName.length<1 || userName.length>10 || containSpecial.test(userName)){
        $("#userName").removeClass("is-valid");
        $("#userName").addClass("is-invalid");
        return false;
    }else {
        $("#userName").removeClass("is-invalid");
        $("#userName").addClass("is-valid");
    }
    return true;
}

function initEmailUser(){
    $("#email-user").attr("placeholder", "邮箱/用户名");
    var userName = $("#email-user").val();
    //判断邮箱是否为空
    if(userName === "" || userName === null){
        $("#email-user").removeClass("is-valid");
        $("#email-user").addClass("is-invalid");
        return false;
    }else {
        $("#email-user").removeClass("is-invalid");
        $("#email-user").addClass("is-valid");
    }
    return true;
}

function initEmail(){
    $("#userEmail").attr("placeholder", "邮箱");
    //匹配规则
    var reg = /^(?=\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$).{0,64}$/;
    //获取邮箱
    var emailValue = $("#userEmail").val();
    //判断邮箱是否为空
    if(emailValue === "" || emailValue.match(reg) == null){
        $("#userEmail").removeClass("is-valid");
        $("#userEmail").addClass("is-invalid");
        return false;
    }else {
        $("#userEmail").removeClass("is-invalid");
        $("#userEmail").addClass("is-valid");
    }
    return true;
}


function initPwd(){
    $("#pwd").attr("placeholder", "密码");
    var pwd = $("#pwd").val();
    let containSpecial = RegExp(/[^A-Za-z0-9]/g);
    //判断邮箱是否为空
    if(pwd === "" || pwd.length<6 || pwd.length>10 || containSpecial.test(pwd)){
        $("#pwd").removeClass("is-valid");
        $("#pwd").addClass("is-invalid");
        return false;
    }else {
        $("#pwd").removeClass("is-invalid");
        $("#pwd").addClass("is-valid");
    }
    return true;
}

function initReloadPwd(){
    $("#reloadPwd").attr("placeholder", "再次确认密码");
    var pwd = $("#pwd").val();
    var reloadpwd = $("#reloadPwd").val();
    if(reloadpwd === null || reloadpwd === "" || reloadpwd !== pwd){
        $("#reloadPwd").removeClass("is-valid");
        $("#reloadPwd").addClass("is-invalid");
        return false;
    }else {
        $("#reloadPwd").removeClass("is-invalid");
        $("#reloadPwd").addClass("is-valid");
    }
    return true;
}

function initEmailCode(){
    $("#emailCode").attr("placeholder", "4位验证码");
    var emailcode = $("#emailCode").val();
    if(emailcode === null || emailcode.length !== 4){
        $("#emailCode").removeClass("is-valid");
        $("#emailCode").addClass("is-invalid");
        return false;
    }else {
        $("#emailCode").removeClass("is-invalid");
        $("#emailCode").addClass("is-valid");
    }
    return true;
}

//忘记密码发送验证码
function sendForgetEmailCode(){
    var pwd = initPwd();
    var reloadPwd = initReloadPwd();
    var email = initEmail();
    if(!( pwd && reloadPwd && email)){
        return;
    }

    sendEmailCodeTime(2);

    $(".step-div ul li:nth-child(2)").addClass("step-success");
}

//注册发送验证码
function sendEmailCode(data){
    var userName = initUserName();
    var pwd = initPwd();
    var reloadPwd = initReloadPwd();
    var email = initEmail();
    if(!(userName && pwd && reloadPwd && email)){
        return;
    }

    sendEmailCodeTime(1);
}

function sendEmailCodeTime(type){
    //禁用按钮
    $(".emailCodeButton").addClass("disabled");

    var emailUrl;
    //忘记密码
    var email =  $("#userEmail").val();
    if(type === 2){
        emailUrl = '/blog/blogViewController/sendEamilForgetCode?email='+email;
    }else {
        //注册
        emailUrl = '/blog/blogViewController/sendEamilCode?email='+email;
    }

    $.ajax({
        type: 'GET',
        url: emailUrl , //要请求的url地址
        dataType: "json",
        headers: {
            "Content-Type": 'application/json'
        },//设置请求头
        success: function (result) {
            if(result.code==="200"){
                if(type === 2){
                    setLocalStorage('malongxiaozhan-forget', result.data)
                }else {
                    //注册
                    setLocalStorage('malongxiaozhan-register', result.data)
                }
                daojishi();
            }else {
                $('#myModal').modal('show');
                $('.modal-title').html("发送失败");
                $('.modal-body').html(result.msg);
                //启用按钮
                $(".emailCodeButton").removeClass("disabled");
            }
        }
    });


}

function daojishi(){
    //1分钟倒计时
    var InterValObj;
    var s=59;
    InterValObj = window.setInterval(function(){
        if(s<10){
            //如果秒数少于10在前面加上0
            $('.emailCodeButton').html('0'+s);
        }else{
            $('.emailCodeButton').html(s);
        }
        s--;
        if(s<0){
            //如果秒数少于0就结束
            window.clearInterval(InterValObj);
            //启用按钮
            $(".emailCodeButton").removeClass("disabled");
            $('.emailCodeButton').html("发送验证码");

        }
    },1000);
}

//注册用户
function registerUser(){
    var userName = initUserName();
    var pwd = initPwd();
    var reloadPwd = initReloadPwd();
    var email = initEmail();
    var emailCode = initEmailCode();
    if(!(userName && pwd && reloadPwd && email && emailCode)){
        return false;
    }

    //禁用按钮
    $(".registerButton").addClass("disabled");
    var formData = $(".needs-validation").serializeJson();

    formData.sendId = getLocalStorage('malongxiaozhan-register', expLogin);
    $.ajax({
        type: 'POST',
        url: '/blog/blogViewController/userEamilRegister',
        dataType: "json",
        async: false,
        data: JSON.stringify(formData),
        headers: {
            "Content-Type": 'application/json'
        },//设置请求头
        success: function (result) {
            $('#myModal').modal('show');
            if(result.code === '200'){
                $('.modal-title').html("注册成功");
                $('.modal-body').html("点击登录跳转登录页");
                $('.toLogin').show();
            }else {
                $('.modal-title').html("注册失败");
                $('.modal-body').html(result.msg);
            }
        }
    });

    //启用按钮
    $(".registerButton").removeClass("disabled");
}

//用户登录
function loginUser(){
    var emailUser = initEmailUser();
    var pwd = initPwd();
    if(!(emailUser  && pwd )){
        return false;
    }

    //禁用按钮
    $(".loginUserButton").addClass("disabled");
    var formData = {};
    formData.userEmail = $('#email-user').val();
    formData.passwd = $('#pwd').val();
    $.ajax({
        type: 'POST',
        url: '/blog/blogViewController/userEamilLogin',
        dataType: "json",
        data: JSON.stringify(formData),
        async: false,
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        headers: {
            "Content-Type": 'application/json'
        },//设置请求头
        success: function (result) {
            if(result.code === '200'){
                setLocalStorage('malongxiaozhan-user-jwt', result.data.jwt);
                setLocalStorage('malongxiaozhan-user-userName', result.data.userName);
                window.location.href = content_url+"/index.html";
            }else {
                $('#loginModel').modal('show');
                $('.modal-title').html("登录失败");
                $('.modal-body').html(result.msg);
            }
        },
        error: function (e){
            console.info(e);
        }
    });


    //启用按钮
    $(".loginUserButton").removeClass("disabled");
}

//修改密码
function changePasswd(){
    var pwd = initPwd();
    var reloadPwd = initReloadPwd();
    var email = initEmail();
    var emailCode = initEmailCode();
    if(!( pwd && reloadPwd && email && emailCode)){
        return false;
    }

    //禁用按钮
    $(".changePasswdButton").addClass("disabled");

    var formData = $(".forgetForm").serializeJson();
    formData.sendId = getLocalStorage('malongxiaozhan-forget', expLogin);
    $.ajax({
        type: 'POST',
        url: '/blog/blogViewController/changePassByEmail',
        dataType: "json",
        async: false,
        data: JSON.stringify(formData),
        headers: {
            "Content-Type": 'application/json'
        },//设置请求头
        success: function (result) {
            $('#myModal').modal('show');
            if(result.code === '200'){
                $('.modal-title').html("修改成功");
                $('.modal-body').html("点击登录跳转登录页");
                $('.toLogin').show();
            }else {
                $('.modal-title').html("修改失败");
                $('.modal-body').html(result.msg);
            }
        }
    });

    //启用按钮
    $(".changePasswdButton").removeClass("disabled");
}

function toLogin(){
    window.location.href = content_url+"/index.html?model=login";
}

$.fn.serializeJson=function(){
    var serializeObj={};
    var array=this.serializeArray();
    // var str=this.serialize();
    $(array).each(function(){
        if(serializeObj[this.name]){
            if($.isArray(serializeObj[this.name])){
                serializeObj[this.name].push(this.value);
            }else{
                // 将元素变为 数组 ，hobby : ['音乐','体育']
                serializeObj[this.name]=[serializeObj[this.name],this.value];
            }
        }else{
            serializeObj[this.name]=this.value;
        }
    });
    return serializeObj;
};